<template>
  <div class="search-suggestion">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"

      @load="onLoad"
    >
      <van-cell v-for="(item,index) in suggestions " :key="index"
      @click="$emit('seach',item)"
      >
<span slot="title" v-html="highlight(item)"></span>
      </van-cell>
    </van-list>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search.js'
// lodash 支持按需加载，有利于打包结果优化
// 引入防抖动
import { debounce } from 'lodash'
export default {
  name: 'SearchResult',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      suggestions: [] // 联想建议数据列表

    }
  },
  computed: {},
  watch: {

    searchText: {
      deep: true,
      immediate: true,
      handler: debounce(async function () {
        try {
          const { data } = await getSearchSuggestions(this.searchText)
          this.suggestions = data.data.options
        } catch (error) {
          this.$toast('获取失败')
        }
      }, 200)

    }
  },
  created () {},
  mounted () {},
  methods: {
    onLoad () {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      setTimeout(() => {
        for (let i = 0; i < 10; i++) {
          this.list.push(this.list.length + 1)
        }

        // 加载状态结束
        this.loading = false

        // 数据全部加载完成
        if (this.list.length >= 40) {
          this.finished = true
        }
      }, 1000)
    },
    // 处理高亮
    highlight (text) {
      const str = `<span class="active">${this.searchText}</span>`
      // 如果需要根据数据变量动态的创建正则表达式，则手动 new RegExp
      // RegExp 正则表达式构造函数
      //    参数1：匹配模式字符串，它会根据这个字符串创建正则对象
      //    参数2：匹配模式，要写到字符串中
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, str)
    }
  }
}
</script>

<style scoped lang="less">
/deep/ .van-cell__title{
  .active{
    color: #3296fa;
  }
}
</style>
